<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>星枢AI中台</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading"> 登录 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { login } from "@/apis/user";

export default defineComponent({
  name: "LoginPage",
  setup() {
    const router = useRouter();
    const store = useStore();
    const loginFormRef = ref();
    const loading = ref(false);

    const loginForm = reactive({
      username: "",
      password: "",
    });

    const rules = {
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    };

    const handleLogin = async () => {
      try {
        await loginFormRef.value.validate();
        loading.value = true;

        const resp = await login(loginForm.username, loginForm.password);
        if (!resp || resp.code !== 200) {
          ElMessage.error(resp.message || "用户名或密码错误");
          return;
        }
        console.log(resp);
        const data = resp.data;
        store.commit("SET_TOKEN", data.token);
        store.commit("SET_USER_INFO", { username: data.userInfo.username });
        ElMessage.success("登录成功");
        router.push("/assistant");
      } catch (error) {
        console.error("登录失败:", error);
      } finally {
        loading.value = false;
      }
    };

    return {
      loginForm,
      rules,
      loginFormRef,
      loading,
      handleLogin,
    };
  },
});
</script>

<style lang="scss" scoped>
.login-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;

  .login-card {
    width: 400px;
    padding: 20px;

    h2 {
      text-align: center;
      margin-bottom: 30px;
      color: #303133;
    }

    .el-button {
      width: 100%;
    }
  }
}
</style>
